import { useEffect, useState } from 'react';

import { Button, Space, Form, Row, Col, Table, Select, Popconfirm, Image } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import { QueryAdvListParams, Adv, AdvPlaceType } from './services';
import { queryAdvList, delAdv, AdvInfoType, AdvShow, AdvOpenType } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { jump2target } from '@/utils/common';

const AdvPage: React.FC = () => {
  const access = usePageAccess()
  const [searchForm] = Form.useForm<QueryAdvListParams>()
  const [searchParams, setSearchParams] = useState<QueryAdvListParams>({
    pageNum: 1, pageSize: 10,
  })
  const advList = useRequest(() => queryAdvList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delAdvAsync } = useRequest(delAdv, {manual: true})

  const openEditPage = (title: string, type: string, record?: Adv) => {
    if (type === 'edit') {
      sessionStorage.setItem('_advRecord', JSON.stringify(record))
    }
    jump2target(`/advertisement/list/edit?type=${type}&id=${record?.id || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/advertisement/list/edit_title', title)
  }

  const onFinish = (formValues: QueryAdvListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const columns: ColumnsType<Adv> = [

    {
      title: '展示位置',
      dataIndex: 'placeType',
      width: 120,
      render: val => val && AdvPlaceType[val],
    },
    {
      title: '关联类型',
      dataIndex: 'infoType',
      width: 120,
      render: val => val && AdvInfoType[val],
    },
    {
      title: '关联信息名称',
      dataIndex: 'infoName',
      width: 120,
      render: val => val || '--',
    },
    {
      title: '展示方式',
      dataIndex: 'openType',
      width: 120,
      render: val => val && AdvOpenType[val],
    },
    {
      title: '是否展示',
      dataIndex: 'isShow',
      width: 120,
      render: val => val && AdvShow[val],
    },
    {
      title: '权重',
      dataIndex: 'power',
      width: 80,
    },
    {
      title: '图片',
      dataIndex: 'pic',
      width: 200,
      render: val => val && <Image style={{height: 60}} src={val} />
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 140,
      render: createTime => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 140,
      render: (id: number, record) => {
        return <Space>
          <a onClick={() => openEditPage('编辑广告', 'edit', record)}>编辑</a>
          <Access accessible={record.isShow === AdvShow.展示}>
            <Popconfirm
              title={`确定隐藏该广告吗?`}
              onConfirm={() => delAdvAsync({id: record.id, status: 2}).then(advList.refresh)}
              okText="隐藏"
              cancelText="取消"
            >
              <a>隐藏</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.isShow === AdvShow.隐藏}>
            <Popconfirm
              title={`确定展示该广告吗?`}
              onConfirm={() => delAdvAsync({id: record.id, status: 1}).then(advList.refresh)}
              okText="展示"
              cancelText="取消"
            >
              <a>展示</a>
            </Popconfirm>
          </Access>
          <Popconfirm
            title={`确定删除该广告吗?`}
            onConfirm={() => delAdvAsync({id: record.id, status: 3}).then(advList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      advList.refresh()
    }
    window.addEventListener('refreshAdvList', refresh)
    return () => {
      window.removeEventListener('refreshAdvList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加广告', 'add')}>添加广告</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchAdvForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='展示位置' name='placeType'>
                  <Select placeholder='请选择' options={enum2options(AdvPlaceType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='关联类型' name='infoType'>
                  <Select placeholder='请选择' options={enum2options(AdvInfoType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='展示方式' name='openType'>
                  <Select placeholder='请选择' options={enum2options(AdvOpenType)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='是否展示' name='isShow'>
                  <Select placeholder='请选择' options={enum2options(AdvShow)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={advList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Adv>
          rowKey='id'
          loading={advList.loading}
          dataSource={advList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: advList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default AdvPage;
